package com.itheima.aop;

import com.alibaba.fastjson.JSONObject;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.util.JwtUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * ClassName:OperateLog
 * Package:com.itheima.aop
 * Description:
 *
 * @Author 老大
 * @Create 2024/5/9 15:29
 * @Version 1.0
 */
@Component
@Aspect
public class OperateLogCalc {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.itheima.anno.Log)")
    public Object operateLog(ProceedingJoinPoint joinPoint) throws Throwable {
        String jwt = request.getHeader("token");
        int operateUserId = (int) JwtUtils.parseJWT(jwt).get("id");
        LocalDateTime now = LocalDateTime.now();        //操作时间
        String name = joinPoint.getTarget().getClass().getSimpleName();   //操作类名
        String methodName = joinPoint.getSignature().getName();     //操作方法名
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        String resultValue = JSONObject.toJSONString(result);
        long end = System.currentTimeMillis();

        long costTime = end - start;

        OperateLog operateLog = new OperateLog( null, operateUserId , now , name , methodName , methodParams , resultValue , costTime);
        operateLogMapper.insert(operateLog);

        return result;
    }
}
